#!/usr/bin/env bash
set -e

################## 可自定义变量 ##################
WORKDIR=/opt/l2tp-vpn
# 使用命令行参数或默认值
VPN_USER=${1:-username}        # 如果未传入参数1，默认username
VPN_PASS=${2:-password}        # 如果未传入参数2，默认password
VPN_PSK=${3:-my_psk}           # 如果未传入参数3，默认my_psk
TIMEZONE=Asia/Shanghai         # 时区设置
IMAGE=hwdsl2/ipsec-vpn-server  # VPN服务器镜像
###################################################

echo "==> 使用配置："
echo "    VPN用户名: $VPN_USER"
echo "    VPN密码: $VPN_PASS"
echo "    VPN预共享密钥: $VPN_PSK"
echo "    TIMEZONE: $TIMEZONE"

echo "==> 1. 设置宿主机时区为 $TIMEZONE"
sudo timedatectl set-timezone "$TIMEZONE" || {
  sudo ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime
  echo "$TIMEZONE" | sudo tee /etc/timezone
}

echo "==> 2. 设置必要的系统参数 (修复网络命名空间错误)"
sudo modprobe af_key
sudo sysctl -w net.ipv4.ip_forward=1
sudo sysctl -w net.ipv4.conf.all.accept_redirects=0
sudo sysctl -w net.ipv4.conf.all.send_redirects=0
sudo sysctl -w net.ipv4.conf.default.rp_filter=0
sudo sysctl -w net.ipv4.conf.default.accept_source_route=0
sudo sysctl -w net.ipv4.conf.default.send_redirects=0
sudo sysctl -w net.ipv4.icmp_ignore_bogus_error_responses=1

echo "==> 3. 创建工作目录 $WORKDIR"
sudo mkdir -p "$WORKDIR" && cd "$WORKDIR"

echo "==> 4. 生成 docker-compose.yml (修复网络配置错误)"
cat <<EOF | sudo tee docker-compose.yml >/dev/null
version: '2.2'
services:
  vpn:
    image: ${IMAGE}
    container_name: l2tp-vpn
    restart: unless-stopped
    privileged: true
    cap_add:
      - NET_ADMIN
    environment:
      - VPN_IPSEC_PSK=${VPN_PSK}
      - VPN_USER=${VPN_USER}
      - VPN_PASSWORD=${VPN_PASS}
      - TZ=${TIMEZONE}
    volumes:
      - /lib/modules:/lib/modules:ro
      - ./vpn-data:/etc/ipsec.d
    ports:
      - "500:500/udp"
      - "4500:4500/udp"
      - "1701:1701/udp"
EOF

echo "==> 5. 启动VPN容器"
sudo docker-compose up -d

echo "==> 6. 等待服务初始化(约15秒)..."
sleep 15

echo "======================================================"
echo "L2TP/IPsec VPN 已成功部署！"
echo "  服务器地址: $(curl -s 4.ipw.cn || curl -s http://ip.3322.net)"
echo "  用户名: ${VPN_USER}"
echo "  密码: ${VPN_PASS}"
echo "  预共享密钥: ${VPN_PSK}"
echo "  协议: L2TP/IPsec"
echo ""
echo "客户端连接注意事项:"
echo "  * 确保服务器防火墙开放UDP端口: 500, 4500, 1701"
echo "  * Windows客户端可能需要修改注册表:"
echo "    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PolicyAgent]"
echo "    \"AssumeUDPEncapsulationContextOnSendRule\"=dword:00000002"
echo "======================================================"
echo "测试命令: docker logs l2tp-vpn"